<template>
  <a-modal
    v-model:visible="visible"
    draggable
    @before-ok="handleBeforeOk"
    @cancel="handleChangeVisible"
  >
    <template #title> {{ title }}</template>
    <a-form
      ref="formRef"
      :model="formData"
      class="form"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item
        field="answer"
        label="回答"
        :rules="[{ required: true, message: '请输入回答' }]"
      >
        <a-textarea v-model="formData.answer" placeholder="请输入回答" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { answerQuestion } from '@/api/common-problem-management';
  import { Message } from '@arco-design/web-vue';

  defineProps({
    title: {
      type: String,
      default: '回答问题',
    },
  });
  const formRef = ref();
  const visible = ref(false);
  const form = () => {
    return {
      id: '',
      answer: '',
    };
  };
  const formData = ref(form());

  function handleChangeVisible(id: string) {
    visible.value = !visible.value;
    if (!visible.value) {
      formData.value = form();
      formRef.value.resetFields();
      formRef.value.clearValidate();
    }
    if (visible.value && id) formData.value.id = JSON.parse(JSON.stringify(id));
  }

  const emit = defineEmits(['refresh']);

  function handleBeforeOk(done: any) {
    formRef.value.validate((valid: any) => {
      if (valid) {
        done(false);
      } else {
        answerQuestion(formData.value)
          .then(() => {
            Message.success('操作成功');
            emit('refresh');
            done();
          })
          .catch(() => {
            done(false);
          });
      }
    });
  }
  defineExpose({ handleChangeVisible });
</script>
